package org.zoomdev.zoom.protobuf.modules;

import io.protostuff.ByteArrayInput;
import io.protostuff.ProtostuffOutput;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;

public final class UnknownArraySchema implements ISchema {

    public static final UnknownArraySchema IUnknownArray = new UnknownArraySchema(IUnknownSchema.IUnknownSchema);

    private final ISchema schema;

    public UnknownArraySchema(ISchema schema) {
        this.schema = schema;
    }

    @Override
    public void write(ProtostuffOutput output, int index, Object data, boolean repeat) throws IOException {
        Object[] array = (Object[]) data;
        for (Object value : array) {
            if (value == null) {
                continue;
            }
            schema.write(output, index++, value, false);
        }
    }

    @Override
    public Object mergeFrom(ByteArrayInput input) throws IOException {
        ArrayList list = new ArrayList();
        while (true) {
            int number = input.readFieldNumber(null);
            if (number == 0) {
                break;
            }
            int index = input.readInt32();
            number = input.readFieldNumber(null);
            if (number == 0) {
                break;
            }
            ISchema schema = IUnknownSchemaRegistry.getSchema(index);
            list.add(schema.mergeFrom(input));
        }

        Object array = Array.newInstance(Object.class, list.size());
        return list.toArray((Object[]) array);
    }
}
